#!/bin/bash

declare -a args

examples() {
    echo -e "\nExamples:\n"
    echo -e "change hikv settings such as cluster name, listen address:"
    echo -e "\t$0 -h 1.1.1.1 setconfig --cluster-name test4 --dc dc4 --rack rack4 --seeds 2.2.2.5"
    echo -e "\t$0 -h 1.1.1.1 scfg --cluster-name test4 --dc dc4 --rack rack4 --seeds \"2.2.2.2,1.1.1.1\""
    echo -e "Only change cluster_name:"
    echo -e "\t$0 -h 1.1.1.1 setconfig --cluster-name test1"
    echo -e "set keyspace, user, and dc replicas distribution:"
    echo -e "\t$0 -h 1.1.1.1 account --keyspace ks1 --user user1 --dc-replicas \"'dc1': 3, 'dc2': 3\""

    echo -e "do sanity checking, ignore SSD and bond0 settings:"
    echo -e "\t$0 -h 1.1.1.1 sanity --ignore-ssd --ignore-bond0"
    echo -e "profiling for 10 seconds and generate FlameGraph:"
    echo -e "\t$0 -h 1.1.1.1 perf --sleep 10"
}

usage() {
    echo "$0 <-h host> [--help] <subcommand> <options>"
}

if [ $# = 0 ] || [ "$1" = "--help" ]; then
    usage
    cd hikv-admin
    ./hikv-admin.sh -h
    examples
    exit
fi

case $1 in
-h)
    host=$2
    shift 2
    ;;
*)
    echo "$0: invalid parameters"
    exit 1
    ;;
esac

i=0
for arg in "$@"; do
    args[i]=$(printf '%q' $arg)
    i=$((i+1))
done

#printf '> %s\n' "${args[@]}"

# not support `read`
run_local_script() {
    ssh -q -o "StrictHostKeyChecking no" root@$host 'bash /dev/stdin' "${args[@]}" < hikv-admin.sh
}

run_remote_script() {
    echo "copy hikv-admin.sh to remote nodes ..."
    scp -q -r hikv-admin root@$host:/usr/local
    # Passing parameter in this way works
    ssh -q root@$host "cd /usr/local/hikv-admin; ./hikv-admin.sh "${args[@]}""

    # using single quote will not work !
    #ssh -q root@$host 'cd /usr/local/hikv-admin; ./hikv-admin.sh "${args[@]}"'
}

run_remote_script
